cap log close
log using "${logpath}count_firms.log", replace

/*******************************************************************************
count_firms.do

This code counts firms and riders adjusted for 20% sample
*******************************************************************************/

use "${cleandatapath}ambulancetaxis_claims_0719.dta", clear 

* Keep positive NPI-months before prior auth
qui keep if ride > 0 & month <= mofd(mdy(12, 1, 2014))

** Count unique patients and scale 
bysort bene_id: gen pat_flag=_n==1
egen observed_pats=total(pat_flag)
qui su observed_pats
scalar total_pats=`r(mean)'/0.2


** Count firms -- tag patients
bysort npi bene_id: gen firmpat_flag=_n==1
bysort npi: egen firm_size=total(firmpat_flag)

** Count firms 
bysort npi: gen firm_flag=_n==1
collapse (sum) firms=firm_flag, by(firm_size)

** Count implied firms 
gen implied_firms=firms+firms*(1-0.2)^firm_size
egen total_implied_firms=total(implied_firms)
qui su total_implied_firms
scalar total_firms = `r(mean)'

** Print out variables 
di "Total Firms = " total_firms // Referenced in Appendix J.2, Bullet 2
di "Average Riders per Firm = " total_pats / total_firms // Referenced in Footnote 24 and Appendix J.2, Bullet 4

log close